﻿using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
using System.IO;
using System;
using System.Xml;

namespace CalculateResistance
{
    /// <summary>
    /// XML文本通用解释器
    /// </summary>
    public class XmlHelper
    {
        private const string EncodePattern = "<[^>]+?encoding=\"(?<enc>[^<>\\s]+)\"[^>]*?>";
        private static readonly Encoding DefEncoding = Encoding.UTF8;
        private static readonly Regex RegRoot = new Regex("<(\\w+?)[ >]", RegexOptions.Compiled);
        private static readonly Regex RegEncode = new Regex(EncodePattern,
                                                            RegexOptions.Compiled | RegexOptions.IgnoreCase);
        private static readonly Dictionary<string, XmlSerializer> Parsers = new Dictionary<string, XmlSerializer>();
        #region 解析器

        static Encoding GetEncoding(string input)
        {
            var match = RegEncode.Match(input);
            if (match.Success)
            {
                try
                {
                    return Encoding.GetEncoding(match.Result("${enc}"));
                }
                // ReSharper disable EmptyGeneralCatchClause
                catch (Exception)
                // ReSharper restore EmptyGeneralCatchClause
                {
                    throw new Exception("获取XML编码失败,可能未设置编码。");
                }
            }
            return DefEncoding;
        }

        /// <summary>
        /// 解析XML文件
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="fileName">文件名</param>
        /// <returns>类的实例</returns>
        public T ParseFile<T>(string fileName) where T : class, new()
        {
            var info = new FileInfo(fileName);
            if (!info.Extension.Equals(".xml", StringComparison.CurrentCultureIgnoreCase) || !info.Exists)
            {
                throw new ArgumentException("输入的文件名有误！");
            }
            string body;

            using (Stream stream = File.Open(fileName, FileMode.Open, FileAccess.Read))
            {
                using (TextReader reader = new StreamReader(stream, DefEncoding))
                {
                    body = reader.ReadToEnd();
                }
            }
            var enc = GetEncoding(body);
            if (!Equals(enc, DefEncoding))
            {
                var data = DefEncoding.GetBytes(body);
                var dest = Encoding.Convert(DefEncoding, enc, data);
                body = enc.GetString(dest);
            }
            return Parse<T>(body, enc);
        }

        /// <summary>
        /// 将对象序列化为XML文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="obj">对象</param>
        /// <returns></returns>
        /// <exception cref="ArgumentException">文件名错误异常</exception>
        public bool SaveFile(string fileName, object obj)
        {
            return SaveFile(fileName, obj, DefEncoding);
        }

        /// <summary>
        /// 将对象序列化为XML文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="obj">对象</param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException">文件名错误异常</exception>
        public bool SaveFile(string fileName, object obj, Encoding encoding)
        {
            var info = new FileInfo(fileName);
            if (!info.Extension.Equals(".xml", StringComparison.CurrentCultureIgnoreCase))
            {
                throw new ArgumentException("输入的文件名有误！");
            }
            if (obj == null) return false;
            var type = obj.GetType();
            var serializer = GetSerializer(type);

            using (Stream stream = File.Open(fileName, FileMode.Create, FileAccess.Write))
            {
                using (TextWriter writer = new StreamWriter(stream, encoding))
                {
                    serializer.Serialize(writer, obj);
                }
            }
            return true;
        }
        static XmlSerializer GetSerializer(Type type)
        {
            XmlSerializer serializer;
            serializer = new XmlSerializer(type);
            return serializer;
        }
        /// <summary>
        /// 解析文本
        /// </summary>
        /// <typeparam name="T">需要解析的类</typeparam>
        /// <param name="body">待解析文本</param>
        /// <returns>类的实例</returns>
        public T Parse<T>(string body) where T : class, new()
        {
            var encoding = GetEncoding(body);
            return Parse<T>(body, encoding);
        }

        /// <summary>
        /// 解析文本
        /// </summary>
        /// <typeparam name="T">需要解析的类</typeparam>
        /// <param name="body">待解析文本</param>
        /// <param name="encoding"></param>
        /// <returns>类的实例</returns>
        public T Parse<T>(string body, Encoding encoding) where T : class, new()
        {
            var type = typeof(T);
            var rootTagName = GetRootElement(body);

            var serializer = GetSerializer(type);
            object obj;
            using (Stream stream = new MemoryStream(encoding.GetBytes(body)))
            {
                obj = serializer.Deserialize(stream);
            }
            if (obj == null) return null;
            try
            {
                var rsp = (T)obj;
                return rsp;
            }
            catch (InvalidCastException)
            {
                var rsp = new T();
                var pisr = typeof(T).GetProperties();
                var piso = obj.GetType().GetProperties();
                foreach (var info in pisr)
                {
                    var info1 = info;
                    foreach (var value in from propertyInfo in piso where info1.Name.Equals(propertyInfo.Name) select propertyInfo.GetValue(obj, null))
                    {
                        info.SetValue(rsp, value, null);
                        break;
                    }
                }
                return rsp;
            }
        }

        private static XmlSerializer BuildSerializer(Type type)
        {
            var rootAttrs = new XmlAttributes { XmlRoot = new XmlRootAttribute(type.Name) };
            var attrOvrs = new XmlAttributeOverrides();
            attrOvrs.Add(type, rootAttrs);
            try
            {
                return new XmlSerializer(type, attrOvrs);
            }
            catch (Exception e)
            {
                throw new Exception("类型声明错误！" + e);
            }
        }

        /// <summary>
        /// 解析未知类型的XML内容
        /// </summary>
        /// <param name="body">Xml文本</param>
        /// <param name="encoding">字符编码</param>
        /// <returns></returns>
        public object ParseUnknown(string body, Encoding encoding)
        {
            var rootTagName = GetRootElement(body);
            var array = AppDomain.CurrentDomain.GetAssemblies();
            Type type = null;
            foreach (var assembly in array)
            {
                type = assembly.GetType(rootTagName, false, true);
                if (type != null) break;
            }
            if (type == null)
            {
                //Logger.GetInstance().Warn("加载 {0} XML类型失败！ ", rootTagName);
                return null;
            }
            var serializer = GetSerializer(type);
            object obj;
            using (Stream stream = new MemoryStream(encoding.GetBytes(body)))
            {
                obj = serializer.Deserialize(stream);
            }

            var rsp = obj;
            return rsp;
        }
        /// <summary>
        /// 用XML序列化对象
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public string Serialize(object obj)
        {
            return Serialize(obj, DefEncoding);
        }
        /// <summary>
        /// 用XML序列化对象
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public string Serialize(object obj, Encoding encoding)
        {
            if (obj == null) return string.Empty;
            var type = obj.GetType();
            var serializer = GetSerializer(type);
            var builder = new StringBuilder();
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.Encoding = encoding;
            settings.NamespaceHandling = NamespaceHandling.OmitDuplicates;
            using (MemoryStream stream = new MemoryStream())
            {
                using (XmlWriter writer = XmlWriter.Create(stream, settings))
                {
                    serializer.Serialize(writer, obj);
                    writer.Close();
                }
                stream.Position = 0;
                using (StreamReader reader = new StreamReader(stream, encoding))
                {
                    return reader.ReadToEnd();
                }
            }
        }
        #endregion

        /// <summary>
        /// 获取XML响应的根节点名称
        /// </summary>
        private static string GetRootElement(string body)
        {
            var match = RegRoot.Match(body);
            if (match.Success)
            {
                return match.Groups[1].ToString();
            }
            throw new Exception("Invalid XML format!");
        }

    }
}
